//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/2/2.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    //底部工具条约束
    var toolbarBottonCons: NSLayoutConstraint?
    /// 图片选择器高度约束
    var photoViewHeightCons: NSLayoutConstraint?
    //监听方法
    @objc private func selectPicture(){
        
        //1.关闭键盘
        textView.resignFirstResponder()
        //2.调整图片选择器的高度
        photoViewHeightCons?.constant = screenHeight * 0.6
        
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func inputEmotion() {
        //1.关闭键盘
        textView.resignFirstResponder()
        //2.1设置inputView
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        //2.2调整图片选择器的高度
        photoViewHeightCons?.constant = screenHeight * 0
        //3.开启键盘
        textView.becomeFirstResponder()
    }
    
    @objc private func send() {
        
        let text = textView.emoticonAttributedText()
        let image = photoSelectorVC.pictureImages.first
        
        NetworkTools.shareNetworkTools().sendStatus(text, image: image, successCallback: { (status) in
            //提示用户发送成功
            SVProgressHUD.showSuccessWithStatus("发布成功", maskType: SVProgressHUDMaskType.Black)
            //关闭发送界面
            self.close()
            }) { (error) in
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        //将键盘控制器添加为当前控制器的子控制器
        addChildViewController(emoticonVC)
        addChildViewController(photoSelectorVC)
        
        setupUI()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if photoViewHeightCons?.constant == 0 {
            //主动显示键盘
            textView.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        //主动隐藏键盘
        textView.resignFirstResponder()
    }
    
    private func setupUI() {
        //初始化导航条
        setupNavBar()
        //初始化文本
        setupTextView()
        //初始化工具条
        setupToolBar()
        //初始化图片选择器
        setupPhotoView()
        //注册通知
        registerNotification()
    }
    
    //添加通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知响应方法
    @objc private func keyboardWillChange(notification: NSNotification) {
        //获取动画事件
        let duartion = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //修改 toolBar约束 获取键盘高度
        toolbarBottonCons?.constant = -screenHeight + rect.origin.y
        //取出键盘的动画节奏
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        UIView.animateWithDuration(duartion) { () -> Void in
            //设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.integerValue)!)
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }
    

    
    //MARK: -懒加载控件
    private lazy var textView: UITextView = {
       let textView = UITextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.darkGrayColor()
        //设置小键盘消失模式
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        textView.alwaysBounceVertical = true
        return textView
    }()
    /// 占位文本
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    
    ///工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    /// 表情键盘控制器
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { [unowned self] (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    
    ///图片选择器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        
        return label
    }()
}

private let maxTipTextLenght = 10

// MARK: - 设置textView监听代理代理
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChangeSelection(textView: UITextView) {
        //设置展位文本隐藏
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //当前已经输入的内容长度
        let count = textView.emoticonAttributedText().characters.count
        let reduce = maxTipTextLenght - count
        tipLabel.textColor = reduce > 0 ? UIColor.darkGrayColor() : UIColor.redColor()
        tipLabel.text = reduce == maxTipTextLenght ? "" : "\(reduce)"
    }
}


// MARK: - 设置UI
extension ComposeViewController {
    
    private func setupPhotoView() {
        //1.添加图片选择器
        view.insertSubview(photoSelectorVC.view, belowSubview: toolBar)
        //2.布局图片选择器
        let cons = photoSelectorVC.view.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: screenWidth, height: 0))
        photoViewHeightCons = photoSelectorVC.view.xmg_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    //设置底部工具栏
    private func setupToolBar() {
        view.addSubview(toolBar)
        view.addSubview(tipLabel)
        
        //设置toolBar的按钮以及点击事件
        var items = [UIBarButtonItem]()
        
        //添加UIBarButtonItem
        let itemSettings = [["imageName":"compose_toolbar_picture", "actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "inputEmotion"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            
            items.append(item)
            //实例化弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        //设置约束
        let cons = toolBar.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: screenWidth, height: 44))
        toolbarBottonCons = toolBar.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
//        tipLabel.text = "140"
        tipLabel.xmg_AlignVertical(type: XMG_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -10, y: -10))
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        
        //添加占位文本
        textView.addSubview(placeHolderLabel)
        
        //设置约束
        textView.xmg_Fill(view)
        
        placeHolderLabel.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    //设置导航条
    private func setupNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(ComposeViewController.close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(ComposeViewController.send))
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        
        //添加导航栏 发布信息的UIlabel
        let tittleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccount.loadAccount()?.screen_name ?? "", size: 14, color: UIColor.lightGrayColor())
        //添加子视图
        titleView.addSubview(tittleLabel)
        titleView.addSubview(nameLabel)
        
        //设置约束
        tittleLabel.xmg_AlignInner(type: XMG_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: titleView, size: nil)
        
    }
}